import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Form, message, DatePicker } from 'antd';
import Question from '../../../../components/Question';
import AreaBasicChart from '../../../../components/Chart/AreaBasicChart';
import LineStackChart from '../../../../components/Chart/LineStackChart';
import ProgressBox from '../../../../components/ProgressBox';
import services from '../../../../services/api';
import moment from 'moment';
import AppProductEventForm from '../../../../components/AppProductEventForm'
import './index.less';
moment.locale('zh-cn');

const { RangePicker } = DatePicker;

function IndicatorStatistic(props) {
  const [requests, setRequests] = useState([
    {
      name: '指标调用总量',
      key: 'total',
      value: 0
    },
    {
      name: '指标计算量',
      key: 1,
      value: 0
    },
    {
      name: '指标取值量',
      key: 2,
      value: 0
    }
  ]);
  const [featureTop, setFeatureTop] = useState([]);
  const [featureTrend, setFeatureTrend] = useState([]);
  const [dates, setDates] = useState([]);
  const [value, setValue] = useState([
    moment().startOf('week'),
    moment()
  ]);
  const form = props.form

  useEffect(() => {
    freshQueryList()
  }, [])

  function getData(params) {
    services.indicator.statistics(params).then(res => {
      if (res.code === 0) {
        setRequests(res.data.requests);
        setFeatureTop(res.data.feature_top);
        setFeatureTrend(res.data.feature_trend);
      } else {
        message.error(res.msg)
      }
    });
  }

  function formChange(type, value) {
    freshQueryList()
  }

  function freshQueryList(curValue) {
    curValue = curValue ? curValue : value
    const dates = {
      start: curValue[0].format('YYYY-MM-DD HH:mm:ss'),
      end: curValue[1].format('YYYY-MM-DD HH:mm:ss')
    }
    getData({
      ...(form.getFieldsValue()),
      ...dates
    });
  }

  const feature = requests.find(it => it.name === '指标调用总量');
  const featureTotal = feature ? feature.value : 0;

  const onDateChange = (value) => {
    setValue(value)
  }

  const onDateOk = (value) => {
    freshQueryList(value)
  }

  const onOpenChange = open => {
    if (open) {
      setDates([]);
    }
  };

  const disabledDate = current => {
    if (dates.length === 1) {
      return (
        current > moment().endOf('day') ||
        current > moment(dates[0]).add(31, 'day') ||
        current < moment(dates[0]).subtract(31, 'day')
      )
    }
    return current > moment().endOf('day')
  };
  const color = ['#c23431', '#808d96', '#61a0a8'];
  return (
    <div>
      <Row type='flex' justify='end' gutter={20}>
        <Col span={12}>
          <AppProductEventForm
            hideLabel={true}
            isAddAll={true}
            form={form}
            app_placeholder='请选择渠道'
            product_placeholder='请选择产品'
            event_placeholder='请选择事件'
            onAppChange={formChange.bind(this)}
            onProductChange={formChange.bind(this)}
            onEventChange={formChange.bind(this)}
          ></AppProductEventForm>
        </Col>
        <Col>
          <RangePicker
            showTime={{
              defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
            }}
            format='YYYY-MM-DD HH:mm:ss'
            placeholder={['起始时间', '结束时间']}
            onChange={onDateChange}
            onCalendarChange={val => {
              setDates(val)}}
            onOk={onDateOk.bind(this)}
            style={{ width: '100%' }}
            onOpenChange={onOpenChange}
            disabledDate={disabledDate}
            ranges={{
              本周: [moment().startOf('week'), moment()],
              近7天: [moment().subtract('days', 6), moment()],
              本月: [moment().startOf('month'), moment()],
              近30天: [moment().subtract('days', 29), moment()]
            }}
            allowClear={true}
            value={value}
          />
        </Col>
      </Row>
      <Row type='flex' jusify='space-between' gutter={20} style={{ marginTop: '20px' }}>
        {requests.map((item, index) => {
          return (
            <Col span={8} key={item.name}>
              <div className='trend-item'>
                <Row type='flex' justify='space-between'>
                  <Col>{item.name}</Col>
                  {item.name === '指标调用总量' && (
                    <Col>
                      <Question
                        title={
                          '关于指标调用系统提供了取值、计算两个接口。举例：指标名称为近一小时登录次数。 调用指标取值接口，可获取到当前近一小时的登录次数。调用指标计算接口，登录次数累加并存储到系统，可供下次指标取值时使用。'
                        }
                      />
                    </Col>
                  )}
                </Row>
                <Row type='flex' justify='space-between' gutter={10} style={{ marginTop: '20px' }}>
                  <Col span={12}>
                    <Row type='flex' gutter={10} justify='start' align='middle'>
                      <Col>
                        <span className='trend-item-num'>{item.value}</span>
                      </Col>
                      <Col>
                        <span>次</span>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={12}>
                    <AreaBasicChart width={145} height={50} color={color[index]} />
                  </Col>
                </Row>
              </div>
            </Col>
          );
        })}

        <Col span={16} style={{ marginTop: '20px' }}>
          <Card title='调用趋势图' bordered={0}>
            <LineStackChart
              width='100%'
              dataSource={featureTrend}
              legend={featureTrend.map(item => item.name)}
              xAxisKey={'index'}
              dataKey={'requests'}
            />
          </Card>
        </Col>
        <Col span={8} style={{ marginTop: '20px' }}>
          <Card title='指标调用排行Top10' bordered={0}>
            <ProgressBox
              leftLabel='指标名称'
              rightLabel='调用次数'
              dataSource={featureTop}
              keyValue={['feature_name', 'hit_times']}
              total={featureTotal}
              boxHeight={455}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
}

export default Form.create()(IndicatorStatistic)